<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
error_reporting(E_ALL & ~(E_NOTICE|E_WARNING ));
class Cart extends MY_Front_Controller {
	public function __construct() {
		parent::__construct();
		
	}
	public function cart_a($selections){
		$prod = explode('#', $selections);
		foreach ($prod as $prod_options){
			$prod_array = explode('_', $prod_options);
			if (!empty($prod_array[0]) && !empty($prod_array[1]) ){
				$this->addToCart($prod_array[0] , true, $prod_array[1]);
			}
		}
		
		$this->index();
	}
	public function addToCart($id, $fromMyOrders = false, $size = false) {
// 		if (!$this->access->getUserId()){
//         	redirect(site_url('user/create/'));
//         }
// 		var_dump($fromMyOrders);
		
   		$this->load->model('product_model');
		$productDetails = $this->product_model->getAll(array('id' => $id))->result();
	
		$imgUrl = $productDetails[0]->url;
		if (empty($imgUrl) AND !empty($productDetails[0]->parent_id)) {
			$parentProductDetails = $this->product_model->getAll(array('id' => $productDetails[0]->parent_id))->result();
			$imgUrl = $parentProductDetails[0]->url;
		}
		$data = array(  'id'        => $id,
						'qty'       => 1,
						'price'     => ($productDetails[0]->special_price > 0 ? ($productDetails[0]->special_price - $productDetails[0]->special_price*$productDetails[0]->promotion_value/100) : ($productDetails[0]->price - $productDetails[0]->price*$productDetails[0]->promotion_value/100)),
						'name'      => $productDetails[0]->name,
						'options'   => array(	'imageUrl' => $imgUrl,
											'metal'    => $productDetails[0]->metal,
											'colour'   => $productDetails[0]->colour,
											'carat_weight' 	  => number_format(round($productDetails[0]->carat_weight,2),2),
											'diamond_size_text' => $productDetails[0]->diamond_size_text,
											'ring_band_width'   => $productDetails[0]->ring_band_width,
											'ring_size' => $fromMyOrders ? $size : $_REQUEST["ring_size"])
		);
		if (isset($_REQUEST["engraving_text"]) && !empty($_REQUEST["engraving_text"])) {
			$data['options']['engraving_text'] = $_REQUEST["engraving_text"];
		}
		if (isset($_REQUEST["special_requirements"]) && !empty($_REQUEST["special_requirements"])) {
			$data['options']["special_requirements"] = $_REQUEST["special_requirements"];
		}
	$this->cart->insert($data);
	
	if ($_REQUEST['fast_comand'] === '1'){
		$this->checkout();
	}else{
		if (!$fromMyOrders) {
			redirect(site_url('cart'));
		}
	}
	
	}
	
	public function updateCart() {
		$this->load->helper('form');
		$countItem = $this->input->post('countItem');
		$data= array();
		for ($i=1; $i<= $countItem; $i++){
			$data[]= array(
				'rowid' => $this->input->post("{$i}_rowid"),
				'qty'   => $this->input->post("{$i}_qty")
				);
		}
		$this->cart->update($data);
		redirect(site_url('cart'));
	}
	
	public function deleteItem($id) {
		$this->load->helper('form');
		$countItem = $this->input->post('countItem');
		$data = array(
			'rowid' => $id,
			'qty'   => 0
		);
		$this->cart->update($data);
		redirect(site_url('cart'));
	}

	public function index(){
// 		if (!$this->access->getUserId()){
//         	redirect(site_url('user/create/'));
//         }
		$data = array();
		$data['backString'] = ($this->session->userdata('product_search_url') ? $this->session->userdata('product_search_url') : '');
	
		$this->template->add_js('application/assets/js/shadowbox.js');
		$this->template->add_css('application/assets/css/shadowbox.css');
		
		$this->template->write_view ( 'content', 'front/cart.php', $data);
		$this->template->render ();
	}
	
	public function checkout(){
		$this->load->model('order_address_model');
		$this->load->model('curier_model');
		$data['address'] = '';
		if ($user = $this->session->userdata('user')){
			$data['address'] = $this->order_address_model->get_by_param(array('user_id' => $user['id']));
		}

		$this->load->library('plati');
			
		$objPlati = new plati();
		
		$objPlati->LoginID = LOGIN_ID_PLAT;
		$objPlati->KeyEnc = KEY_ENCRIP_PLAT_DEMO;
		$objPlati->KeyMod = KEY_ENCRIPT_MOD_PLAT_DEMO;
		
		$objPlati->amount = $this->cart->total() ;
		$objPlati->currency = $this->session->userdata('selected_currency') == "RON" ? $this->session->userdata('selected_currency') : "EUR";
		$objPlati->OrderNumber = 2;
		$objPlati->action = 2;
		switch ($this->session->userdata('selected_country')){
			case 1:
				$objPlati->lang = "en";
				break;
			case 2:
				$objPlati->lang = "ro";
				break;
			case 3:
				$objPlati->lang = "it";
				break;
			case 4:
				$objPlati->lang = "fr";
				break;
			case 5:
				$objPlati->lang = "de";
				break;
			case 8:
				$objPlati->lang = "hu";
				break;
			case 11:
				$objPlati->lang = "es";
				break;
			default:
				$objPlati->lang = "en";
				break;
		}
 	
		$objPlati->OrderString = '<?xml version=\'1.0\' encoding=\'UTF-8\'><start_string>';
		
		foreach ( $this->cart->contents() as $items ){
			 $tempArray = array('product_id' =>$items['id'],
							    'qty'=> $items["qty"],
						        'size'=>$items["options"]['ring_size'],
							    'imageUrl'=>$items["options"]['imageUrl'],
							    'price'=>$items['subtotal']
			 		);
			 if (isset($items["options"]['engraving_text']) && !empty($items["options"]['engraving_text'])){
			 	$tempArray['engraving_text'] = $items["options"]['engraving_text'];
			 }
			 if (isset($items["options"]['special_requirements']) && !empty($items["options"]['special_requirements'])) {
			 	$tempArray['comment'] = $items["options"]['special_requirements'];
			 }
			 $data['content'][] = $tempArray;
			 $objPlati->OrderString .='<item>'.
											'<ProdID>'.$items['id'].'</ProdID>'.
											'<qty>'. $items["qty"].'</qty>'.
											'<itemprice>'.$items["price"].'</itemprice>'.
											'<name>ring</name>'.
											'<period>vid</period>'.
											'<rec_id>vid</rec_id>'.
											'<description>asas</description>'.
											'<pimg>vid</pimg>'.
											'<rec_price>vid</rec_price>'.
											'<vat>22</vat>'.
											'<lang_id>ro</lang_id>'.
											'<stamp>'.date('Y-m-d H:s:i').'</stamp>'.
											'<on_stoc>0</on_stoc>'.
											'<prodtype_id>1</prodtype_id>'.
											'<categ_id>vid</categ_id>'.
											'<merchLoginID>vid</merchLoginID>'.
										'</item>';
		}
					
		$objPlati->OrderString .='<coupon>'.
						'<key>123</key>'.
						'<value>50</value>'.
						'<percent>1</percent>'.
						'<workingname>asdasd</workingname>'.
						'<type>0</type>'.
						'<scop>0</scop>'.
						'<vat>22</vat>'.
					'</coupon>'.
					'<shipping>'.
						'<type>1</type>'.
						'<price>10</price>'.
						'<pimg>asdasdsad</pimg>'.
					'</shipping>'.
				'</start_string>';
		$data['podata'] = $objPlati->InsertHash_Auth();
		$data['curier'] = $this->curier_model->getAll();
		$data['advance_of_maney'] = isset($_REQUEST['aom']) ? $_REQUEST['aom'] : 100;
		
		$this->template->add_js('application/assets/js/shadowbox.js');
		$this->template->add_css('application/assets/css/shadowbox.css');
		$this->template->add_js('application/assets/js/register.js');
		
		$this->template->write_view ( 'content', 'front/checkout.php', $data );
		$this->template->render ();
	}
	
	public function saveBilling(){
		$this->load->model('order_address_model');
		$this->load->model('country_model');
		// for new user 
		$this->load->library('SimpleLoginSecure');
		$this->simpleloginsecure->setUserTable('fe_users');
		$this->simpleloginsecure->setIsAdmin(0);
		$this->load->model('fe_user_model');
		
		$billing = $_REQUEST["billing"];
		if (isset($billing["new_user"]) && $billing["new_user"] == 1){
			$hasher = new PasswordHash(8, false);
			$this->fe_user_model->fields['user_email']	= htmlentities($billing['email']);
			$this->fe_user_model->fields['user_pass'] 	= $hasher->HashPassword($billing['email']);
			$this->fe_user_model->fields['user_date'] 	= date('Y-m-m h:i:s');
			$this->fe_user_model->fields['first_name'] 	= htmlentities($billing['first_name']);
			$this->fe_user_model->fields['last_name'] 	= htmlentities($billing['last_name']);
			$this->fe_user_model->fields['company'] 	= htmlentities($billing['company']);
			$this->fe_user_model->fields['country_id'] 	= htmlentities($billing['country_id']);
			$this->fe_user_model->fields['city'] 	= htmlentities($billing['city']);
			$this->fe_user_model->fields['zip'] 	= htmlentities($billing['postcode']);
			$this->fe_user_model->fields['tel'] 	= htmlentities($billing['tel_number']);
			$this->fe_user_model->fields['fax'] 	= htmlentities($billing['fax']);
			$this->fe_user_model->fields['street'] 	= htmlentities($billing['address']);
			$this->fe_user_model->fields['newsletter'] 	= htmlentities($billing['subscribe']);
			$user = $this->fe_user_model->fields_to_object();
			$user->insert();
				
			$this->simpleloginsecure->login($user->user_email, htmlentities($billing['email']));
		}
		$user = $this->session->userdata('user'); 
	
		 		
		if (empty($billing['address_id'])){
			$this->order_address_model->fields['first_name'] 	= $billing['first_name'];
			$this->order_address_model->fields['last_name'] 	= $billing['last_name'];
			$this->order_address_model->fields['country_id'] 	= $billing['country_id'];
			$this->order_address_model->fields['company'] 		= $billing['company'];
			$this->order_address_model->fields['address'] 		= $billing['address'];
			$this->order_address_model->fields['city']    		= $billing['city'];
			$this->order_address_model->fields['state_provide'] = $billing['state_provide'];
			$this->order_address_model->fields['postcode'] 		= $billing['postcode'];
			$this->order_address_model->fields['tel_number'] 	= $billing['tel_number'];
			$this->order_address_model->fields['fax'] 			= $billing['fax'];
			$this->order_address_model->fields['type'] 			= 1;
			$this->order_address_model->fields['user_id'] 		= $user['id'];
			$this->order_address_model->fields['natural_person']= $billing['natural_person'];
			$this->order_address_model->fields['how_you_found_us']= (isset($billing['how_you_found_us2']))? $billing['how_you_found_us2'] :$billing['how_you_found_us'];
			$this->order_address_model->fields['newsletter'] 	= $billing['subscribe'];
			$billing_1 = $this->order_address_model->fields_to_object();
			$billing['address_id'] = $billing_1->insert();
			$billing['new_address']= true;
		} else {
			$billing = $this->order_address_model->get_by_id($billing['address_id'])->to_array();
			$billing['address_id'] = $billing['id'];
			$billing['new_address']= false;
		}
		$country = $this->country_model->get_by_id($billing['country_id']);
		$billing['country_name'] = $country->name;
		$billing['code_iso_2'] = $country->code_iso_2;
		$billing['email'] = $this->session->userdata('user_email');
		echo json_encode($billing);
	}
	
	public function saveShipping() {
		$this->load->model('order_address_model');
		$this->load->model('country_model');
		$user = $this->session->userdata('user');
	
		$shipping = $_REQUEST["shipping"];
		if (empty($shipping['address_id'])){
			$this->order_address_model->fields['first_name'] 	= $shipping['first_name'];
			$this->order_address_model->fields['last_name'] 	= $shipping['last_name'];
			$this->order_address_model->fields['country_id'] 	= $shipping['country_id'];
			$this->order_address_model->fields['company'] 		= $shipping['company'];
			$this->order_address_model->fields['address'] 		= $shipping['address'];
			$this->order_address_model->fields['city']    		= $shipping['city'];
			$this->order_address_model->fields['state_provide'] = $shipping['state_provide'];
			$this->order_address_model->fields['postcode'] 		= $shipping['postcode'];
			$this->order_address_model->fields['tel_number'] 	= $shipping['tel_number'];
			$this->order_address_model->fields['fax'] 			= $shipping['fax'];
			$this->order_address_model->fields['type'] 			= 2;
			$this->order_address_model->fields['user_id'] 		= $user['id'];
			$shipping_1 = $this->order_address_model->fields_to_object();
			$shipping['address_id'] = $shipping_1->insert();
		} else {
			$shipping = $this->order_address_model->get_by_id($shipping['address_id'])->to_array();
			$shipping['address_id'] = $shipping['id'];
		}
		
		$country = $this->country_model->get_by_id($shipping['country_id']);
		$shipping['country_name'] = $country->name;
		echo json_encode($shipping);
	}
	
	public function saveOrder($request= null ) {
		$this->load->model('affiliate_model');
		$this->load->model('fe_user_model');
		$this->load->model('orders_model');
		$this->load->model('product_model');
		$this->load->model('user_model');
		$this->load->library('parser');
		$this->load->library('exchange');
		$countries = $this->country_model->get_by_params(array('language_id' => $order[0]->language))->result();
		if ($countries[0]->currency_id){
			$currency = $this->currency_model->get_by_id($countries[0]->currency_id)->name;
		}
		$user = $this->session->userdata('user');
		if ($this->session->userdata('idAffiliate')){
			$affiliateObj = $this->affiliate_model->get_by_id($this->session->userdata('idAffiliate'));
		}
		$data = array();
		$data['total'] = $this->cart->total();
		foreach ($this->cart->contents() as $items){
			$data['content'][] = $items;
		}
		$this->orders_model->fields['products'] = json_encode($data);
		$this->orders_model->fields['data_add']  = date('Y-m-d H:i:s');
		$this->orders_model->fields['confirmed'] = 0;
		$this->orders_model->fields['user_id']   = $user['id'];
		$this->orders_model->fields['status']    = 1;
		$this->orders_model->fields['order_type']= $_REQUEST['order_payment_method'];
		$this->orders_model->fields['billing_id']= $_REQUEST['order_billing_id'];
		$this->orders_model->fields['shipping_id']= $_REQUEST['order_shipping_id'];
		$this->orders_model->fields['shipping_method']= $_REQUEST['order_shipping_method'];
		$this->orders_model->fields['advance_of_maney']= $_REQUEST['order_advance_of_maney'];
		$this->orders_model->fields['discount']= $_REQUEST['order_discount'];
		$this->orders_model->fields['language']=  $this->config->item('lang_obj')->id;
		$this->orders_model->fields['country_id']=  $this->session->userdata('selected_country');
		if (isset($affiliateObj->id)){
			$this->orders_model->fields['affiliate_id']=  $affiliateObj->id;
		}
		
		$orders = $this->orders_model->fields_to_object();
		$order_id = $orders->insert();
		
		
		$order = $this->orders_model->getAllOrders($order_id);
		$allProducts = json_decode($order[0]->products);

		$data= array();
		$data['hello_name'] = lang('hello'). ' '. $user['first_name'].' ' . $user['last_name'];
		$data['thank_you_order_text'] =lang('thank_you_order_text');
		$data['email_order_text'] =lang('email_order_text');
		$data['email_order_number'] = lang('your_order'). ' # '. $order_id;
		$data['date'] = date("Y-m-d H:m:i");
		$data['billing_info_text'] = lang('billing_info_text');
		$data['payment_method_tex'] =lang('payment_method_tex');
		$data['shipping_info_text'] = lang('shipping_info_text');
		$data['shipping_method_tex'] = lang('shipping_method_tex');
		$data['billing_address'] = $order[0]->b_first_name .' '. $order[0]->b_last_name. ', <br/>'. $order[0]->b_country . ' ' . $order[0]->b_city . ' ' .$order[0]->b_address ;
		$data['shpping_address'] = $order[0]->s_first_name .' '. $order[0]->s_last_name. ', <br/>'. $order[0]->s_country . ' ' . $order[0]->s_city . ' ' .$order[0]->s_address ;
		$data['payment_method'] = lang('payment_method');
		$data['shipping_method'] = lang('shipping_method');
		$data['additional_info_text'] =lang('additional_info_text');
		$data['additional_info_order_email_text'] =lang('additional_info_order_email_text');
		$data['item'] =lang('item');
		$data['sku'] =lang('sku');
		$data['qty'] =lang('qty');
		$data['subtotal_text'] =lang('subtotal_text');
		$data['shipping'] = 0;
		$data['subtotal'] = $this->exchange->transformPrice($allProducts->total , $currency, true, false, $order[0]->country_id, 0, ($order[0]->natural_person)? false : true);
		$data['total'] = $this->exchange->transformPrice($allProducts->total , $currency, true, false, $order[0]->country_id, 0, ($order[0]->natural_person)? false : true);
		$data['grand_total'] = $this->exchange->transformPrice($allProducts->total , $currency, true, false, $order[0]->country_id,0, ($order[0]->natural_person)? false : true);
		$data['tax'] = $this->exchange->getTax($allProducts->total,$currency );
		$data['product_list'] ='';
	
		foreach ($allProducts->content as $item) {
			$product = $this->product_model->get_by_id($item->id);
			$data['product_list'] .= '<tr>
				<td valign="top" style="border:none;padding:2.25pt 6.75pt 2.25pt 6.75pt;">
				<p ><b>PD071W - 18ct white gold ring with a round diamond in a 6 claw setting-0.20-H-SI2</b>
				</p><p ><b>
				<i>'.lang('size').'
				</b>
				</p>
			<p style="margin-left:36.0pt;" >'.$item->options->ring_size.'</p>
			</td>
			<td valign="top" style="border:none;padding:2.25pt 6.75pt 2.25pt 6.75pt;">
			<p>
			'.$product->sku.'
			</td>
			<td valign="top" style="border:none;padding:2.25pt 6.75pt 2.25pt 6.75pt;">
			<p align="center" style="text-align:center;">'.$item->qty.'
			</p>
			</td>
			<td valign="top" style="border:none;padding:2.25pt 6.75pt 2.25pt 6.75pt;">
			<p align="right" style="text-align:right;" >'.$this->exchange->transformPrice($item->price , $currency, true, false, $order[0]->country_id, $product->promotion_value, ($order[0]->natural_person)? false : true).'</p>
			</td>
			</tr>';
		
		}
		$htmlMessage =  $this->parser->parse('templates/email/order_email', $data, true);
		
		/*$config = array();
		$config['protocol']  = 'smtp';
		$config['smtp_host'] = 'ssl://smtp.googlemail.com';
		$config['smtp_port'] = '465';
		$config['smtp_timeout'] = '30';
		$config['smtp_user'] = 'ist.gombos@gmail.com';
		$config['smtp_pass'] = '1988.10.13';
		$config['charset']  = 'utf-8';
		$config['newline']  = "\r\n";
		$config['mailtype']  = "html";*/
		
		$agents = $this->user_model->get_by_param(array('type_id'=> 2,'language_id'=> $this->config->item('lang_obj')->id ));
		$emails = '';
		$x = 0;
		foreach ($agents as $agent){
			if ($x > 0){
				$emails = $emails.','.$agent->user_email;
			}else{
				$emails = $agent->user_email;
			}
			$x++;
		}
		$emails = $emails. ','.$user['user_email'];
		
// 		$this->load->library('email', $config);
		$this->load->library('email');
		$this->email->initialize(array('mailtype' => 'html', 'protocol' => 'sendmail'));
		$this->email->from('no-repy@royalbijuterii.com', 'royalbijuterii');
		$this->email->to($emails);
		$this->email->subject(lang('order_details_email_subject'));
		$this->email->message($htmlMessage);
		$this->cart->destroy();
		if ($this->email->send()){
			
		}
		
		echo json_encode(array('order_id'=>$order_id)); 
	}
	
	function getCurier($id) {
		$this->load->model('curier_model');
		$data = $this->curier_model->get_by_id($id);
		
		echo json_encode(array('name'=> $data->name , 'tax'=>$data->tax));
	}
	
	function getDiscountPercent() {
		$discountCode = $_REQUEST['code'];
		$this->load->model('discount_model');
		$data = $this->discount_model->get_by_param(array('code'=> $discountCode));
		if (!empty($data)) {
			$newdata = array(
                   'discount_rate'  => $data[0]->percent                  
               );
			$this->session->set_userdata($newdata);
			echo json_encode(array('status'=> 1 , 'msg'=> lang('discount_ok_respoms'), 'percent'=> $data[0]->percent ));
		} else {
			echo json_encode(array('status'=> 0 , 'msg'=> lang('discount_fail_respoms')));
		}
	}

}